package com.lhj.xxsc.seckill.config;

import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.alibaba.csp.sentinel.adapter.servlet.callback.WebCallbackManager;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.xxsc.common.exception.BizCodeEnume;
import com.xxsc.common.utils.R;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 罗惠江
 * @version 1.0
 * @email 1511619294@qq.com
 * @date 2021/2/25 21:26
 */
@Configuration
public class SeckillSentinelConfig {
	public SeckillSentinelConfig(){
		WebCallbackManager.setUrlBlockHandler(new UrlBlockHandler() {
			@Override
			public void blocked(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws IOException {
				R error = R.error(BizCodeEnume.TO_MAX_REQUEST.getCode(), BizCodeEnume.TO_MAX_REQUEST.getMsg());
				httpServletResponse.setCharacterEncoding("UTF-8");
				httpServletResponse.setContentType("application/json");
				httpServletResponse.getWriter().write(JSON.toJSONString(error));
			}
		});
	}
}
